package com.harlan.viewbindingstudy.base.mvp;

import android.app.Activity;
import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.View;

import com.harlan.viewbindingstudy.databinding.ActivityMvpactivityBinding;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;


/**
 * Created by Administrator on 2018-10-16 0016.
 */

public abstract class XActivity<P extends IPresent> extends RxAppCompatActivity implements IView<P> {

    private VDelegate vDelegate;
    private P p;
    protected Activity context;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        ActivityUtils.add(this);
        getP();
        Log.e("backinfo", "布局为空了:" + getViewBinding());
        if (isOpenViewBinding()) {
            setContentView(getViewBinding());
        } else if (getLayoutId() > 0) {
            setContentView(getLayoutId());
            bindEvent();
        } else {
            throw new IllegalArgumentException("You must return a right contentView layout resource Id");
        }


        initData(savedInstanceState);

    }

    /**
     * 获取ViewBinding
     */
    protected abstract View getViewBinding();

    protected VDelegate getvDelegate() {
        if (vDelegate == null) {
            vDelegate = VDelegateBase.create(context);
        }
        return vDelegate;
    }

    protected P getP() {
        if (p == null) {
            p = newP();
        }
        if (p != null) {
            if (!p.hasV()) {
                p.attachV(this);
            }
        }
        return p;
    }

    @Override
    protected void onStart() {
        super.onStart();

    }


    @Override
    protected void onResume() {
        super.onResume();
        getvDelegate().resume();
    }


    @Override
    protected void onPause() {
        super.onPause();
        getvDelegate().pause();
    }

    @Override
    public boolean useEventBus() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (getP() != null) {
            getP().detachV();
        }
        getvDelegate().destory();
        p = null;
        vDelegate = null;
        System.gc();
        ActivityUtils.finishActivity(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (getOptionsMenuId() > 0) {
            getMenuInflater().inflate(getOptionsMenuId(), menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 是否开启了ViewBinding
     */
    protected boolean isOpenViewBinding() {
        return true;
    }

    @Override
    public int getOptionsMenuId() {
        return 0;
    }

    @Override
    public void bindEvent() {

    }


}
